const { ethers } = require("hardhat");

const fs = require('fs');
const path = require('path');

async function main() {
  const [deployer] = await ethers.getSigners();
  console.log(`Deploying contract address: ${deployer.address}`);

  // const RoleSystem = await ethers.getContractFactory('RoleSystem');
  // const roleSystem = await RoleSystem.deploy();

  // // 等待合约部署确认
  // await roleSystem.waitForDeployment();

  // // 获取合约地址
  // const contractAddress = await roleSystem.getAddress();
  // console.log('RoleSystem contract deployed to:', contractAddress);

  // 部署RoleSystem合约
  const RoleSystem = await ethers.getContractFactory("contracts/RoleSystem.sol:RoleSystem");
  roleSystem = await RoleSystem.deploy();
  await roleSystem.waitForDeployment();
  console.log('RoleSystem contract deployed to:', roleSystem.getAddress());

  // 部署MedicalRecord合约
  const MedicalRecord = await ethers.getContractFactory("MedicalRecord");
  medicalRecord = await MedicalRecord.deploy(await roleSystem.getAddress());
  await medicalRecord.waitForDeployment();
  console.log('MedicalRecord contract deployed to:', medicalRecord.getAddress());

  // 将地址写入前端可访问的文件
  const contractsDir = path.join(__dirname, "..", "src", "contracts");
  if (!fs.existsSync(contractsDir)) fs.mkdirSync(contractsDir);

  fs.writeFileSync(
    path.join(contractsDir, "contract-address.json"),
    JSON.stringify({ YourContractName: contractAddress }, null, 2)
  );
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });